<template>
  <div>
    <h1>监听单个ref变量</h1>
    <h2>{{count}}</h2>
    <button @click="increment">+</button>
    <hr>
    <h1>监听多个ref变量</h1>
    <h2>成绩:{{score}}</h2>
    <button @click="updateScore">更改成绩</button>

    <h2>健康值:{{health}}</h2>
    <button @click="updateHealth">更改健康值</button>

  </div>
</template>
<!-- 
  组合式API实现watch
  1、watch来监听单个ref变量
 -->
<script lang='ts'>
import {ref,reactive,watch} from 'vue'
export default{
 setup(){
  //定义响应式数据
  let count=ref<number>(0)
  //定义方法用来更新响应式数据
  const increment:()=>void=()=>{
    count.value++
  }
  /*
    单个监听ref变量的语法
    watch(arg1,arg2,arg3)
    arg1:你要监听的响应式的数据或者计算属性，比如ref变量名: count
    arg2：监听后的回调方法  (arg1,arg2)=>{}  回调函数的参数1是变化后的值，回调函数的参数2是更新之前的值
    arg3:对象，用来设置监听的相关配置的  {immidite:true} ,可省略
  */
  watch(count,(arg1,arg2)=>{
    console.log(arg1,arg2);
  },{immediate:true})
  console.log('***************************************');

   let score=ref<number>(60)
   let health=ref<number>(80)
   
   const updateScore:()=>void=()=>{
      score.value+=5
   }
   const updateHealth:()=>void=()=>{
      health.value-=1
   }

   /**
    * 监听多个ref变量语法
    *  watch([ref1变量，ref2变量],(newval,oldval)=>{},{})
  */
   watch([score,health],(newval,oldval)=>{
    console.log('成绩的变化:',newval[0],oldval[0]);
    console.log('健康值的变化:',newval[1],oldval[1]);
   })
  
   
  return{
    count,
    increment,
    score,
    health,
    updateScore,
    updateHealth
  }
 }
}
</script>

<style lang='scss' scoped>
</style>